<!--
 要情管理-要情管理：指令下发
 @Author: zhanbh
 @Date: 2021-04-15
-->
<template>
  <div style="background: #fff; padding: 20px">
    <edit-form ref="form" label-width="calc(5em + 18px)" :model="form" :fields="fields" :rules="rules">
      <template #item-jsdwdmList>
        <dg-select disabled v-if="jsdwdmList" v-model="jsdwdmListLabel" :data="constant.BM_DEPT" clearable multiple />
        <el-cascader
          v-else
          :disabled="!!jsdwdmList"
          style="width: 100%"
          :props="{ multiple: true }"
          v-model="form.jsdwdmList"
          :options="constant.BM_DEPT"
          :show-all-levels="false"
          filterable
          clearable
          placeholder="请选择或者输入内容进行搜索"
        />
      </template>
      <template #item-fileHolderList>
        <dg-upload v-model="form.fileHolderList" :server-url="'./'" size="30m" tip-msg="上传文件限制大小为 30M">
          <el-button type="primary" plain>上传文件</el-button>
          <template slot="fileList" slot-scope="{ type, name, size }">
            <i :class="`dg-icon-${type}`"></i>
            {{ `${name} (${size / 1024})KB` }}
          </template>
        </dg-upload>
      </template>
    </edit-form>
    <module-card>
      <template #header>补录</template>  <!-- TODO：数据获取接口调错 -->
      <comm-table ref="table" class="table" :data="data" :columns="columns" :pagination="false" :page-size="0">
        <template slot-scope="{ row }">
          <div>
            <dg-radio-group
              v-model="row.isOpen"
              :data="[
                { label: '是', value: '1' },
                { label: '否', value: '0' }
              ]"
              size="small"
              call-off
            ></dg-radio-group>
          </div>
        </template>
      </comm-table>
    </module-card>
  </div>
</template>

<script>
import ModuleCard from '@/components/layout/module-card';
import EditForm from '@@/edit-form';
import { mapState } from 'vuex';
import { toOrder, leaderCommentFindAll} from '@/api/common';
import { value2Level,generateTimeReqestNumber} from '@/utils/common';
import { getFlowDetail } from '@/api/common';

export default {
  name: 'Order',
  components: {
    EditForm,
    ModuleCard
  },
  props: {
    zllx: {
      type: String
    },
    jsdwdmList: {
      type: Array,
      deault: () => []
    }
  },
  data() {
    // 验证最晚反馈时间不让选择此刻以前的
      var validateTime = (rule, value, callback) => {
         if(value){
        let time=value.replace(/\-| |:/g,"").slice(0,12);
        let currTime=generateTimeReqestNumber();
        if (time <= currTime) {
          callback(new Error('选择时间必须大于当前时间'));
        } else {
          callback();
        }
         }else{
          callback();
         }
      };

    return {
      pickerOptions: {
          // 限制最晚反馈时间不让选择此刻以前的
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
      condition: null,
      loading: false,
      data: [],
      jsdwdmListLabel: [],
      columns: [
        { label: '序号', type: 'index', width: 70 },
        { label: '批阅人', prop: 'psrName' },
        { label: '批阅时间', prop: 'pssj' },
        { label: '批阅内容', prop: 'psnr' },
        { label: '补录人', prop: 'psrName' },
        { label: '补录时间', prop: 'pssj' },
        { label: '是否公开', type: 'operate' }
      ],
      rules: {
        zllx: [{ required: true, message: '请选择指令类型', trigger: 'blur' }],
        jsdwdmList: [{ required: true, message: '请选择接收单位', trigger: 'blur' }],
        zwfksj: [{type:'string', validator: validateTime, trigger: 'change' }]
      },
      timeShortBtns: [
        {
          text: '1小时',
          time: '+60m'
        },
        {
          text: '2小时',
          time: '+1h'
        },
        {
          text: '6小时',
          time: '+3h'
        },
        {
          text: '12小时',
          time: `+6h`
        },
        {
          text: '24小时',
          time: `+12h`
        },
        {
          text: '36小时',
          time: `+18h`
        }
      ],
      form: {
        zllx: '',
        zwfksj: '',
        zlbz: '',
        jsdwdmList: '',
        nxdzl: '',
        fileHolderList: []
      },
      
    };
  },
  computed: {
    fields() {
      const vm = this;
      return [
        {
          prop: 'zllx',
          label: '指令类型',
          col: 12,
          tag: 'dg-select',
          tagBind: {
            filterable: true,
            disabled: !!vm.zllx,
            data: vm.constant.BM_ZLLX
          }
        },
        {
          prop: 'zwfksj',
          label: '最晚反馈时间',
          col: 12,
          bind: {
            labelWidth: 'calc(7em + 12px)'
          },
          tag: 'dg-date-picker',
          tagBind: {
            type: 'datetime',
            select: 'show',
            isSelect: true,
            shortBtns: vm.timeShortBtns,
            placeholder: '请选择最晚反馈时间',
            valueFormat: 'yyyyMMddHHmm',
            format: 'yyyy-MM-dd HH:mm',
            pickerOptions: vm.pickerOptions,
            
          }
        },

        {
          prop: 'jsdwdmList',
          label: '接收单位'
          // tag: 'dg-select',
          // tagBind: {
          //   disabled: !!vm.jsdwdmList,
          //   filterable: true,
          //   lazyLoad: true,
          //   data: vm.constant.BM_DEPT,
          //   multiple: true
          // }
        },
        {
          prop: 'nxdzl',
          label: '拟下达指令',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 3,
            placeholder: '请输入内容',
            maxlength: '1000',
            showWordLimit: true
          }
        },
        {
          prop: 'zlbz',
          label: '备注',
          tag: 'el-input',
          tagBind: {
            type: 'textarea',
            rows: 3,
            placeholder: '请输入内容',
            maxlength: '1000',
            showWordLimit: true
          }
        },
        {
          prop: 'fileHolderList',
          label: '附件'
        }
      ];
    },

    ...mapState(['constant'])
  },
  watch: {
    'constant.BM_DEPT': {
      deep: true,
      immediate: true,
      handler(val) {
        this.jsdwdmListLabel = [];
        if (this.jsdwdmList && this.jsdwdmList.length) {
          this.jsdwdmList.forEach((item) => {
            const labels = value2Level(val, item);
            this.jsdwdmListLabel.push(labels[labels.length - 1]);
          });
        }
      }
    }
  },
  mounted() {
    this.form.zllx = this.zllx;
    this.form.jsdwdmList = this.jsdwdmList;
    this.$store.dispatch('getConstant', ['BM_ZLLX', 'DM_SEX']);
    this.$store.dispatch('getConstantTree', ['BM_DEPT']);
    this.flowId = this.$route.params.id;

    this.condition = {
      flowId: {
        value: this.flowId,
        op: '='
      }
    };
    leaderCommentFindAll(this.flowId).then(({ data }) => {
      this.data = data;
    });
    
    // 如果为市局指挥用户==0101，则拟下达指令自动获取签收时的呈报意见内容展示(传的是flowid)
    // 只有要情管理-指令、线索管理-情报线索信息：指令、请求研判 才显示
    let curDw=this.$store.state.user.info.dept; // 获取当前用户单位等级
     if (this.$route.params.isEcho && curDw=='0101') {
      getFlowDetail(this.flowId).then(({data}) => {
        let cbyjValue= `${data.signInVO.cbyj}` == "null" ? `-` : `${data.signInVO.cbyj}`; // 呈报意见
        let xxbsValue= `${data.signInVO.xxbs}` == "null" ? `-` : `${data.signInVO.xxbs}`; // ，信息报送
        let nxdzlValue= `${data.signInVO.nxdzl}` == "null" ? `-` : `${data.signInVO.nxdzl}`; // ，拟下达指令
        this.form.nxdzl = `呈报意见：${cbyjValue}，信息报送：${xxbsValue}，拟下达指令：${nxdzlValue}`;
        this.form.zlbz = `${data.signInVO.bz}`== "null" ? `-` : `${data.signInVO.bz}`;
      });
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.$refs.form.validate((valid) => {
        if (valid) {
          const ldpscyxxList = this.data.map((item) => {
            return {
              id: item.id,
              isOpen: item.isOpen
            };
          });
          this.loading = true;
          const jsdwdmList = this.jsdwdmList
            ? this.jsdwdmList
            : this.form.jsdwdmList.map((item) => item[item.length - 1]);
          toOrder({
            flowid: this.flowId,
            zlly: this.$route.params.zlly,
            ...this.form,
            ldpscyxxList,
            zwfksj: this.form.zwfksj.slice(0, 16),
            jsdwdmList
          })
            .then(() => {
              this.loading = false;
              this.$message.success('下发成功');
              this.$router.go(-1);
            })
            .catch(() => {
              this.loading = false;
              this.$message.warning('下发失败');
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.yq-order {
  height: calc(100vh - 11rem);
}
.edit-form {
  max-width: 1000px;
}
</style>
